package com.woniu.user.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.user.controller.form.CheckTimeForm;
import com.woniu.user.dao.AccountDao;
import com.woniu.user.exception.WebException;
import com.woniu.user.exception.WebExceptionCode;
import com.woniu.user.model.Account;
import com.woniu.user.model.Book;
import com.woniu.user.model.Coach;
import com.woniu.user.dao.CoachDao;
import com.woniu.user.model.Occupy;
import com.woniu.user.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.user.service.dto.CoachInfoDto;
import com.woniu.user.util.BeanCopyUtil;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 教练特有信息表 服务实现类
 * </p>
 *
 * @author Silas
 * @since 2023-02-15
 */
@Service
public class CoachServiceImpl extends ServiceImpl<CoachDao, Coach> implements CoachService {
    @Resource
    private CoachDao coachDao;

    @Resource
    private AccountDao accountDao;

    @Resource
    private OccupyService occupyService;

    @Resource
    private AccountService accountService;

    @Resource
    private LessonService lessonService;

    @Resource
    private BookService bookService;

    @Override
    public void beCoach(Coach coach) {
        save(coach);
    }

    @Override
    public void setStyle(int accountFromToken, String style) {
        Account account = accountDao.selectById(accountFromToken);
        account.setType("教练");
        accountDao.updateById(account);
        Coach coach = coachDao.selectOne(new QueryWrapper<Coach>().eq("account_id", accountFromToken));
        coach.setStyle(style);
        save(coach);
    }

    @Override
    public Page<CoachInfoDto> query(String condition, Integer current, Integer size) {
        // 分页代码片段
        Page<CoachInfoDto> page = new Page<>(current == null ? 1 : current, size == null ? 4 : size);
        List<CoachInfoDto> coachInfoDto = new ArrayList<>();
        QueryWrapper<Coach> queryWrapper = new QueryWrapper<>();
            List<CoachInfoDto> query = coachDao.query(condition);
//            queryWrapper.eq("realname",condition)
//                    .or().eq("style",condition)
//                    .or().eq("venue_name",condition);
//            return coachDao.query(condition, page);
            page.setRecords(query);
            return page;

    }

    // 查询所有教练（分页）
    @Override
    public IPage<CoachInfoDto> findAll(Page<Coach> pageInfo) {
        return this.baseMapper.list(pageInfo);
    }

    // 确认时间
    @SneakyThrows
    @Override
    public void checkTime(CheckTimeForm form, Integer userId) {
        // 先检查时间是否被占用 若未占用则写入occupy 再生成book信息 等待教练确认
        Integer coachId = form.getCoachId();
        System.out.println("------------"+coachId);
        String date = form.getDate();
        String time = form.getTime();
        date = date.substring(0, 11) + time + ".000Z";
        SimpleDateFormat str2date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        Date rawDate = str2date.parse(date);
        Date newDate = new Date(rawDate.getTime() + (24 * 60 * 60 * 1000));

        // 日期转字符串
        SimpleDateFormat date2str = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        String bookTime = date2str.format(newDate);// 用户选择的预约时间

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        List<Occupy> occupyList = occupyService.list(new QueryWrapper<Occupy>().eq("coach_id", coachId).eq("state", "有效"));
        for (Occupy occupy : occupyList){
            LocalDateTime localDateTime = occupy.getTime();// 数据库表走的占用时间
            String occupyTime = localDateTime.format(dtf);
            if(occupyTime.equals(bookTime)) throw new WebException(WebExceptionCode.COACH_IS_OCCUPIED);
        }

        // 如果能运行到这里不抛异常 说明已经预约成功了 向occupy表中写入信息
        Occupy occupy = new Occupy();
        occupy.setCoachId(coachId);
        String coachName = this.getById(coachId).getRealname();
        System.out.println("------------"+coachName);
        occupy.setCoachName(coachName);
        occupy.setUserId(userId);
        String username = accountService.getById(userId).getUsername();
        occupy.setUserName(username);

        DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        LocalDateTime dateTime = LocalDateTime.parse(bookTime, format);
        occupy.setTime(dateTime);

        Integer lessonId = form.getLessonId();
        String lessonName = lessonService.getById(lessonId).getName();
        occupy.setLessonId(lessonId);
        occupy.setLessonName(lessonName);

        occupy.setState("有效");
        occupyService.save(occupy);
        Integer occupyId = occupyService.getOne(new QueryWrapper<Occupy>().eq("time", dateTime).eq("state", "有效")).getOccupyId();

        // 生成book信息 等待教练确认
        String bookNo = new Snowflake(1, 1).nextIdStr();// 雪花算法生成预约单号
        Book book = new Book();// 预约单
        book.setNo(bookNo);
        book.setUserId(userId);
        book.setUserName(username);
        book.setCoachId(coachId);
        book.setCoachName(coachName);
        book.setCreateTime(LocalDateTime.now());
        book.setLessonId(lessonId);
        book.setLessonName(lessonName);
        book.setLessonTime(dateTime);// 预约的上课时间
        book.setState("待处理");
        book.setOccupyId(occupyId);// 占用表id
        bookService.save(book);

    }

    @Override
    public List<Coach> myCoach(Integer venueId) {
        List<Coach> list = coachDao.selectList(new QueryWrapper<Coach>().eq("venue_id", venueId));
        return list;
    }
}
